from pyparsing import Literal, CaselessLiteral, Word, Upcase, delimitedList, Optional, \
    Combine, Group, alphas, nums, alphanums, ParseException, Forward, oneOf, quotedString, \
    ZeroOrMore, restOfLine

def test( str ):
    print str,"->"
    try:
        tokens = insertSQL.parseString( str )
        print "tokens = ",        tokens
        print "tokens.columns =", tokens.columns
        print "tokens.tables =",  tokens.tables
        print "tokens.values =", tokens.fields
        print "tokens.where =", tokens.where
    except ParseException, err:
        print " "*err.loc + "^\n" + err.msg
        print err
    print


# define SQL tokens
insertStmt = Forward()
insertToken = CaselessLiteral( "insert" )
intoToken   = CaselessLiteral( "into" )
valueToken = CaselessLiteral( "values" )

ident          = Word( alphas, alphanums + "_$" ).setName("identifier")
columnName     = Upcase( delimitedList( ident, ".", combine=True ) )
columnNameList = Group( delimitedList( columnName ) )
valueName = Upcase( delimitedList( ident, ".", combine=True ) )
valueNameList = Group( delimitedList( valueName ) )
tableName      = Upcase( delimitedList( ident, ".", combine=True ) )
tableNameList  = Group( delimitedList( tableName ) )

whereExpression = Forward()
and_ = CaselessLiteral("and")
or_ = CaselessLiteral("or")
in_ = CaselessLiteral("in")

E = CaselessLiteral("E")
binop = oneOf("= != < > >= <= eq ne lt le gt ge like", caseless=True)
arithSign = Word("+-",exact=1)
realNum = Combine( Optional(arithSign) + ( Word( nums ) + "." + Optional( Word(nums) )  |
                                                         ( "." + Word(nums) ) ) +
            Optional( E + Optional(arithSign) + Word(nums) ) )
intNum = Combine( Optional(arithSign) + Word( nums ) +
            Optional( E + Optional("+") + Word(nums) ) )

columnRval = realNum | intNum | quotedString | columnName # need to add support for alg expressions
whereCondition = Group(
    ( columnName + binop + columnRval ) |
    ( columnName + in_ + "(" + delimitedList( columnRval ) + ")" ) |
    ( columnName + in_ + "(" + insertStmt + ")" ) |
    ( "(" + whereExpression + ")" )
    )
whereExpression << whereCondition + ZeroOrMore( ( and_ | or_ ) + whereExpression )

# define the grammar
insertStmt      << ( insertToken + intoToken + tableNameList.setResultsName("tables") +
                   Optional( "(" + columnNameList.setResultsName("columns") + ")") +
                   valueToken + "(" + valueNameList.setResultsName("fields") + ")" +
                   Optional( Group( CaselessLiteral("where") + whereExpression ), "" ).setResultsName("where") )

insertSQL = insertStmt
insertSQL.validate()

# define Oracle comment format, and ignore them
oracleSqlComment = "--" + restOfLine
insertSQL.ignore( oracleSqlComment )


test( "Insert into sdfsdf(a,b,c) values(a,b,c)" )
